<!--
 * @Description: 选择农场页面
-->
<template>
  <div class="choose-company">
    <Header />
    <!-- 选择系统 -->
    <div class="system-choose-modal" :class="{ active: showSystemChooseModal }">
      <div class="system-choose-box">
        <div class="system-choose-title">
          选择基地
          <!-- {{ routerPath == '/choose-company' ? '(生产)' : '(溯源)' }} -->
        </div>
        <div ref="sweiperBox" class="sweiperBox">
          <div class="swiper mySwiper">
            <div class="swiper-wrapper">
              <div class="swiper-slide" @click="item.homeBaseName && chooseSystem(item)"
                v-for="(item, index) in HomeBaseList" :key="index">
                <div class="img">
                  <img v-if="item.src" :src="item.src" alt="" />
                </div>
                <div class="name">{{ item.homeBaseName }}</div>
              </div>
            </div>
            <div class="swiper-pagination"></div>
          </div>
        </div>
        <!-- <div class="system-content swiper-container">
          <div class="system-list swiper-wrapper">
            <div v-for="(item, index) in HomeBaseList" :key="index" class="system-choose-item swiper-slide"
              @click="item.homeBaseName && chooseSystem(item)">
              <div class="img">
                <img v-if="item.src" :src="item.src" alt="">
              </div>
              <div class="name">{{ item.homeBaseName }}</div>
            </div>
            <div class="swiper-slide"></div>
          </div>
        </div> -->
      </div>
    </div>
  </div>
</template>
<script>
import Header from "@/layout/components/Header/index.vue";
import Swiper from "swiper";
import { removeToken, setToken } from "@/utils/auth";
import router, { productionMgmRouter } from "@/router";
import { transformRoutes } from "@/utils/resetRouter";

import HomeBaseApi from "@/api/basic-info-manage/homeBase";
import UserApi from "@/api/system-settings/user-manage";
import StaffApi from "@/api/basic-info-manage/staff";

export default {
  name: "ChooseCompany",
  components: { Header },
  data() {
    return {
      showSystemChooseModal: false, // 选择系统弹窗
      showTopList: true, // 展示顶级组织
      HomeBaseList: [], // 基地列表
      // true 启用动态路由 false 启用静态路由
      // nowmenutype: permission.nowmenutype,
      nowmenutype: true,
      routerPath: "",
      pathList: [],
    };
  },
  computed: {},
  watch: {
    $router(to) { },
  },
  created() {
    // this.routerPath = this.$route.path
    // this.$route.path = '/choose-company'
  },
  mounted() {
    this.tologin();
    // 获取当前登录用户菜单
    this.authPermissionRoutes();
    // this.queryStaffName()
    if (this.$store.state.permission.addRoutes.length > 0) {
      // 判断是否已经刷新
      history.go(0);
    }
  },
  methods: {
    initSwiper() {
      this.$nextTick(() => {
        let HomeBaseList = this.HomeBaseList;
        let browserWidth = window.innerWidth;
        let slidesPerViewLength =
          HomeBaseList.length > 3 ? 3 : HomeBaseList.length;
        let swiperWidth =
          slidesPerViewLength * (browserWidth / 3 - 100) > browserWidth
            ? browserWidth
            : slidesPerViewLength * (browserWidth / 3 - 100);
        this.$refs.sweiperBox.style.width = swiperWidth + "px";
        new Swiper(".mySwiper", {
          slidesPerView: slidesPerViewLength,
          spaceBetween: 20,
          pagination: {
            el: ".swiper-pagination",
            clickable: true,
          },
        });
      });
    },
    tologin() {
      let tr = this.$route.query;
      if (tr.account) {
        let loginForm = {
          account: decodeURIComponent(tr.account),
          password: tr.password,
        };
        this.$router.push({ path: "/login", query: loginForm });
      }
    },
    // 获取当前登录用户菜单
    async authPermissionRoutes() {
      let routerList = [];
      let routerFlag = sessionStorage.getItem("routerFlag");
      let userType = sessionStorage.getItem("userType");
      let { data } = await UserApi.queryAllPermissionList();
      setToken("staffId", data.staffId);
      setToken("userId", data.userId);
      setToken("account", data.account);
      this.queryStaffName(data.staffId);
      this.getHomeBase(data.staffId);
      if (routerFlag == "OMS") {
        routerList = operateRouter;
      } else {
        if (userType == 2) {
          this.pathList = this.getPath(data.functionPermissionMap.WEB);
          routerList = this.findPathsfilterPath(
            productionMgmRouter,
            this.pathList
          );
        } else {
          routerList = productionMgmRouter;
        }
      }
      console.log(routerList, productionMgmRouter);
      router.addRoutes(transformRoutes(routerList));
    },

    findPathsfilterPath(data, pathToFind) {
      let nodes = JSON.parse(JSON.stringify(data));
      let pathList = [];
      nodes.forEach((item) => {
        if (pathToFind.includes(item.path)) {
          let childList =
            item.children && item.children.length > 0
              ? this.findPathsfilterPath(item.children, pathToFind)
              : [];
          pathList.push({
            ...item,
            children: childList,
          });
        }
      });
      return pathList;
    },
    getPath(routerList) {
      let pathList = [];
      routerList.forEach((router) => {
        pathList.push(router.component);
        if (router.childList && router.childList.length > 0) {
          pathList = pathList.concat(this.getPath(router.childList));
        }
      });
      return pathList;
    },
    queryStaffName(params) {
      if (params) {
        StaffApi.getStaffNameById({ staffId: params }).then((res) => {
          setToken("staffName", res.data);
        });
      }
    },
    // 获取当前用户可查看基地列表
    getHomeBase(e) {
      // 获取顶级组织结构id
      HomeBaseApi.queryByUserId({ staffId: e }).then((res) => {
        if (res.length == 0 || res.data == []) {
          this.$message.warning("该账户下无基地权限，请联系管理员！");
          removeToken("token");
          this.$router.push({ path: "/login" });
        } else {
          let list = res.data || [];
          list = list.map(item=>{return {
            ...item,
            sort:item.sort||0
          }})
          list.sort((a, b) => { return a.sort - b.sort })
          this.HomeBaseList = list;
          this.HomeBaseList.forEach((item, index) => {
            if (item.logoId) {
              this.$set(
                this.HomeBaseList[index],
                "src",
                `${this.$baseurl.fileServiceUrl}base/files/preview?fileId=${item.logoId}`
              );
            }
          });
          this.initSwiper();
        }
      });
    },
    // 选择基地
    chooseSystem(item) {
      setToken("ncOrg", item.ncOrg || '');
      item.code && setToken("companyMark", item.code);
      item.homeBaseId && setToken("homeBaseId", item.homeBaseId);
      item.homeBaseType && setToken("homeBaseType", item.homeBaseType);
      item.homeBaseName && setToken("homeBaseName", item.homeBaseName);
      item.src && setToken("homeBaseImg", item.src);
      localStorage.setItem("ncOrg", JSON.stringify(item.ncOrg || {}));
      //start======对接NC接口
      //     queryBillType,//单据类型条件查询
      //     queryCmCostobject,//成本对象条件查询
      //     queryCustomer,//客户条件查询
      //     queryDefdoc,//品级条件查询
      //     queryDefdoc2,//活鱼品规条件查询
      //     queryIncome,//收款协议条件查询
      //     queryMaterial,//物料条件查询
      //     queryMaterialconvert,//物料辅计量单位条件查询
      // 这里分一点nc基础数据接口请求，在choose-system.vue里也有一点
      // this.$store.dispatch("NcBasicInfo/queryBillType");
      // this.$store.dispatch("NcBasicInfo/queryCmCostobject");
      // this.$store.dispatch("NcBasicInfo/queryCustomer");
      // this.$store.dispatch("NcBasicInfo/queryDefdoc");
      // this.$store.dispatch("NcBasicInfo/queryDefdoc2");
      // this.$store.dispatch("NcBasicInfo/queryIncome");
      // this.$store.dispatch("NcBasicInfo/queryMaterial");
      // this.$store.dispatch("NcBasicInfo/queryMaterialconvert");

      //  end======对接NC接口
      this.$router.push({ name: "EnvironmentalDataMonitoring" });
    },
  },
};
</script>

<style scoped lang="scss">
@import "~@/styles/variables.scss";
$slidebarWidth: 40px;
$highBule: rgb(0, 235, 208);

@keyframes borderbg {
  from {
    border-radius: 0;
  }

  to {
    background-color: #fff;
    color: #333;
    border-radius: 20px;
  }
}

.choose-company {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 100%;

  ::v-deep(.header) {
    flex-shrink: 0;
  }
}

.system-choose-modal {
  position: relative;
  width: 100%;
  height: calc(100% - 68px);
  margin: 0;
  background-image: url("~@/assets/choose-company/back.jpg");
  background-repeat: no-repeat;
  background-position: top center;
  background-size: 100% 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40px;
  opacity: 1;
  transition: all 0.5s;

  // pointer-events: none;
  &.active {
    opacity: 1;
    pointer-events: auto;
  }

  .add-basehome-btn {
    position: absolute;
    top: 10px;
    right: 10px;
    width: 112px;
    height: 26px;
    background: #0480fb;
    box-shadow: 0px 0px 2px 1px rgba(0, 0, 0, 0.26);
    border-radius: 3px;
    color: #fff;
    text-align: center;
    line-height: 26px;
    cursor: pointer;

    .el-icon-plus {
      border: 1px dashed #fff;
      color: #fff;
    }
  }

  .system-choose-box {
    width: 100%;
    height: 100%;
    padding: 12px 0;

    .system-choose-title {
      position: absolute;
      top: 25%;
      left: 50%;
      width: 240px;
      height: 35px;
      color: #fff;
      transform: translate(-50%, -50%);
      background: rgba(0, 0, 0, 0.25);
      border-radius: 7px;
      border: 1px solid #ffffff;
      text-align: center;
      line-height: 32px;
      letter-spacing: 2px;
    }

    .system-content {
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      position: relative;

      .system-list {
        // width: 100%;
        height: 90%;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        // overflow-x: auto;

        .system-choose-item {
          color: #fff;
          width: 360px;
          margin: 0 15px;
          height: 40%;
          border: 1px solid #7cd2ff;
          transition: all 0.5s;
          cursor: pointer;

          .img {
            height: calc(100% - 46px);
            // width: 100%
            background: url("~@/assets/choose-company/ly.jpg") center center no-repeat;
            background-size: 100% 100%;
            display: flex;
            flex-direction: row;
            // flex-wrap: wrap;
            justify-content: center;
            align-content: center;
            align-items: center;

            img {
              width: 100%;
              height: 100%;
            }
          }

          .name {
            text-align: center;
            font-size: 16px;
            height: 46px;
            line-height: 46px;
            background-color: #368dff;
          }

          &:hover {
            transform: scale(1.08);
          }
        }

        .system-around-item {
          width: 0;
          height: 0;
          border: none;
        }
      }
    }
  }
}
</style>

<style lang="scss">
.el-scrollbar__wrap {
  overflow-x: hidden;
}

.is-horizontal {
  display: none;
}

.sweiperBox {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.swiper {
  width: 100%;
  height: 50%;
  top: 30%;
  padding: 30px;
}

.swiper-slide {
  text-align: center;
  font-size: 18px;
  line-height: 40px;
  color: #ffffff;
  transition: all 0.3s;

  .name {
    background: #0089fa;
  }

  .img {
    width: 100%;
    height: 260px;
    background: url("~@/assets/choose-company/ly.jpg") center center no-repeat;

    img {
      display: block;
      width: 100%;
      height: 260px;
      object-fit: cover;
    }
  }
}

.swiper-slide:hover {
  transform: scale(1.05);
  cursor: pointer;
}
</style>
